package cz.spock.parser.service;

import java.util.ArrayList;

import org.springframework.stereotype.Service;

import cz.spock.core.service.BaseService;
import cz.spock.exception.InvalidInputException;
import cz.spock.parser.entity.RuleSet;
import cz.spock.parser.entity.TripletPattern;

@Service
public class RuleSetService extends BaseService {
    
    public RuleSet findByName(String name) {
        if(name == null || name.isEmpty()) return null;
        return dao.ofy().query(RuleSet.class).filter("name", name).get();
    }
    
    /**
     * creates list of triplets, overrides existing
     * 
     * @param rs
     * @return
     */
    public RuleSet createTransientListOfTriplets(RuleSet rs) {
        if(rs == null) return null;
        if(rs.getRulesId() == null) return rs;        
        rs.setRules(new ArrayList<TripletPattern>());
        for(Long l : rs.getRulesId()) {
            TripletPattern tp = dao.ofy().find(TripletPattern.class, l);
            if(tp != null) rs.getRules().add(tp);
        }
        return rs;
    }
    
    public RuleSet setName(String name, RuleSet rs) {
        if(rs == null) return null;
        if(name == null) return rs;
        if(!isNameUnique(name)) {
            throw new InvalidInputException("Name must be unique.", 400);
        }
        rs.setName(name);
        return rs;
    }
    
    public RuleSet setJson(String json, RuleSet rs) {
        if(rs == null) return null;
        if(json == null) return rs;
        rs.setName(json);
        return rs;
    }
    
    public RuleSet addTriplet(Long tripletId, RuleSet rs) {
        if(rs == null) return null;
        if(tripletId == null) return rs;
        rs.getRulesId().add(tripletId);
        return rs;
    }
    
    public RuleSet deleteTriplet(Long tripletId, RuleSet rs) {
        if(rs == null) return null;
        if(tripletId == null) return rs;
        rs.getRulesId().remove(tripletId);
        return rs;
    }
    
    public RuleSet save(RuleSet rs) {
        if(rs == null) return null;
        rs.setId(dao.put(rs).getId());
        return rs;
    }
    
    public boolean isNameUnique(String name) {
        if(name == null) return false;
        if(dao.ofy().query(RuleSet.class).filter("name", name).get() == null) {
            return false;
        } else return true;
    }
    
    public String toJson(RuleSet rs) {
        
        return null;
    }
    

}
